<template>
  <div class="dashboard">
    <h1>仪表盘</h1>
    
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: #409EFF;">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.scriptCount }}</div>
              <div class="stat-label">脚本数量</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: #67C23A;">
              <el-icon><SuccessFilled /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.successCount }}</div>
              <div class="stat-label">成功执行</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: #E6A23C;">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.pendingCount }}</div>
              <div class="stat-label">等待执行</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: #F56C6C;">
              <el-icon><WarningFilled /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.failedCount }}</div>
              <div class="stat-label">执行失败</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="charts-row">
      <el-col :span="12">
        <el-card header="脚本语言分布">
          <div v-if="languageStats.length > 0" class="chart-container">
            <div v-for="stat in languageStats" :key="stat.language" class="language-stat">
              <div class="language-info">
                <span class="language-name">{{ getLanguageName(stat.language) }}</span>
                <span class="language-count">{{ stat.count }} 个</span>
              </div>
              <el-progress 
                :percentage="Math.round((stat.count / stats.scriptCount) * 100)" 
                :color="getLanguageColor(stat.language)"
              />
            </div>
          </div>
          <div v-else class="no-data">
            暂无数据
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card header="最近执行日志">
          <el-table :data="safeRecentLogs" style="width: 100%">
            <el-table-column prop="script.name" label="脚本名称" />
            <el-table-column label="语言" width="80">
              <template #default="scope">
                <el-tag size="small" :type="getLanguageType(scope.row.script?.language)">
                  {{ getLanguageName(scope.row.script?.language) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="executed_at" label="执行时间" width="180">
              <template #default="scope">
                {{ formatDate(scope.row.executed_at) }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="quick-actions-row">
      <el-col :span="24">
        <el-card header="快速操作">
          <div class="quick-actions">
            <el-button type="primary" @click="$router.push('/scripts')" size="large">
              <el-icon><DocumentAdd /></el-icon>
              创建新脚本
            </el-button>
            <el-button @click="$router.push('/scripts')" size="large">
              <el-icon><Document /></el-icon>
              管理脚本
            </el-button>
            <el-button @click="$router.push('/execution-logs')" size="large">
              <el-icon><List /></el-icon>
              查看日志
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import api from '../services/api'
import { ensureArray, cleanScriptData, cleanExecutionLogData } from '../utils/validation'

export default {
  name: 'Dashboard',
  setup() {
    const router = useRouter()
    
    const stats = ref({
      scriptCount: 0,
      successCount: 0,
      pendingCount: 0,
      failedCount: 0
    })
    
    const scripts = ref([])
    const recentLogs = ref([])

    // 安全的计算属性，确保返回数组
    const safeRecentLogs = computed(() => {
      return Array.isArray(recentLogs.value) ? recentLogs.value : []
    })

    // 修复 languageStats 计算属性
    const languageStats = computed(() => {
      try {
        // 确保 scripts.value 是数组
        const scriptsArray = Array.isArray(scripts.value) ? scripts.value : []
        
        const languageMap = {}
        scriptsArray.forEach(script => {
          // 确保 script 存在且有 language 属性
          if (script && typeof script === 'object') {
            const lang = script.language || 'unknown'
            languageMap[lang] = (languageMap[lang] || 0) + 1
          }
        })
        
        return Object.entries(languageMap).map(([language, count]) => ({
          language,
          count
        })).sort((a, b) => b.count - a.count)
      } catch (error) {
        console.error('计算语言统计时出错:', error)
        return []
      }
    })

    const fetchStats = async () => {
  try {
    const [scriptsRes, logsRes] = await Promise.all([
      api.get('/scripts/'),
      api.get('/execution-logs/?limit=10')
    ])
    
    // 使用验证工具确保数据安全
    scripts.value = ensureArray(scriptsRes.data).map(cleanScriptData)
    stats.value.scriptCount = scripts.value.length
    
    const logs = ensureArray(logsRes.data).map(cleanExecutionLogData)
    
    // 安全的统计计算
    stats.value.successCount = logs.filter(log => log.status === 'success').length
    stats.value.pendingCount = logs.filter(log => 
      log.status === 'pending' || log.status === 'running'
    ).length
    stats.value.failedCount = logs.filter(log => log.status === 'failed').length
    
    recentLogs.value = logs
  } catch (error) {
    console.error('获取统计信息失败:', error)
    ElMessage.error('获取统计信息失败')
    
    // 确保在错误情况下也有合理的默认值
    scripts.value = []
    recentLogs.value = []
    stats.value = {
      scriptCount: 0,
      successCount: 0,
      pendingCount: 0,
      failedCount: 0
    }
     }
    }

    const getStatusType = (status) => {
      const types = {
        'success': 'success',
        'running': 'primary',
        'pending': 'info',
        'failed': 'danger'
      }
      return types[status] || 'info'
    }

    const getLanguageType = (language) => {
      const types = {
        'python': 'success',
        'shell': 'warning',
        'javascript': 'primary'
      }
      return types[language] || 'info'
    }

    const getLanguageName = (language) => {
      const names = {
        'python': 'Python',
        'shell': 'Shell',
        'javascript': 'JavaScript'
      }
      return names[language] || language || '未知'
    }

    const getLanguageColor = (language) => {
      const colors = {
        'python': '#67c23a',
        'shell': '#e6a23c',
        'javascript': '#409eff'
      }
      return colors[language] || '#909399'
    }

    const formatDate = (dateString) => {
      if (!dateString) return '-'
      try {
        return new Date(dateString).toLocaleString('zh-CN')
      } catch (error) {
        console.error('日期格式化错误:', error)
        return dateString
      }
    }

    onMounted(() => {
      console.log('Dashboard 组件已加载')
      fetchStats()
    })

    return {
      stats,
      recentLogs: safeRecentLogs, // 使用安全的版本
      languageStats,
      getStatusType,
      getLanguageType,
      getLanguageName,
      getLanguageColor,
      formatDate
    }
  }
}
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  height: 120px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
}

.stat-icon .el-icon {
  font-size: 24px;
  color: white;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-label {
  color: #666;
  font-size: 14px;
}

.charts-row {
  margin-top: 20px;
  margin-bottom: 20px;
}

.quick-actions-row {
  margin-top: 20px;
}

.chart-container {
  padding: 10px;
}

.language-stat {
  margin-bottom: 15px;
}

.language-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.language-name {
  font-weight: 500;
}

.language-count {
  color: #666;
  font-size: 12px;
}

.no-data {
  text-align: center;
  color: #999;
  padding: 40px;
}

.quick-actions {
  display: flex;
  gap: 15px;
}

.quick-actions .el-button {
  justify-content: flex-start;
}
</style>
